package com.sen.common.common.controller;

import com.sen.common.common.exception.BusinessException;
import com.sen.common.common.response.MessageResult;
import com.sen.common.common.response.ResultMsgEnum;
import com.sen.common.common.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;


/**
 * @author esJiang
 * @Title 基类, 所有的controller应继承该类
 */
@Slf4j
public abstract class BaseController {

    /**
     * 简化写法，已包括：log、异常
     *
     * @param logName  log名称
     * @param dto      参数
     * @param callable 回调
     * @return
     */
    protected MessageResult exec(String logName, Object dto, ControllerCallable callable) {
        return exec(logName, dto, true, callable);
    }

    /**
     * 简化写法，已包括：log、异常
     *
     * @param logName    log名称
     * @param dto        参数
     * @param showResult 是否展示结果到log，针对list记录过大时，应该false
     * @param callable   回调
     * @return
     */
    protected MessageResult exec(String logName, Object dto, boolean showResult, ControllerCallable callable) {
        MessageResult messageResult = null;
        try {
            log.info(logName + " param:{}", JacksonUtils.toJSONString(dto));
            messageResult = callable.execute();
        } catch (BusinessException e) {
            log.error(e.getRespCodeEnum().toString(), e);
            messageResult = MessageResult.bizFailed(e.getRespCodeEnum());
        } catch (Exception e) {
            log.error(logName + "异常", e);
            messageResult = MessageResult.bizFailed(ResultMsgEnum.SYSTEM_ERROR);
        }
        if (showResult) {
            log.info(logName + " result:{}", JacksonUtils.toJSONString(messageResult));
        } else {
            log.info(logName + " result:{}", JacksonUtils.toJSONString(ResultMsgEnum.SUCCESS));
        }
        return messageResult;
    }
}
